package com.thememaker.lockstyle.bean.command;

import com.thememaker.lockstyle.LockStyleCenterLeftEditUtils;

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * Created by binghui.hang on 2018/2/23.
 * //将屏幕的宽度值赋值给w
 * <VariableCommand name="w" expression="#screen_width"/>
 */
@XmlRootElement(name = "VariableCommand")
public class VariableCommand extends BaseCommand {
    private String name;
    private String expression;
    private String persist;
    private String constString;

    @XmlAttribute(name = "name")
    public String getName() {
        return name;
    }

    @XmlAttribute(name = "expression")
    public String getExpression() {
        return expression;
    }

    @XmlAttribute(name = "persist")
    public String getPersist() {
        return persist;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setExpression(String expression) {
        this.expression = expression;
    }

    public void setPersist(String persist) {
        this.persist = persist;
    }

    @XmlAttribute(name = "const")
    public String getConstString() {
        return constString;
    }

    public void setConstString(String constString) {
        this.constString = constString;
    }

    @Override
    public String toString() {
        Field[] fields = LockStyleCenterLeftEditUtils.getAllFields(this.getClass());
        StringBuffer stringBuffer = new StringBuffer("<");
        XmlRootElement xmlAttribute = this.getClass().getAnnotation(XmlRootElement.class);
        if (xmlAttribute != null) {
            String name = xmlAttribute.name();
            stringBuffer.append(name);
            for (Field field : fields) {
                try {
                    PropertyDescriptor pd = new PropertyDescriptor(field.getName(), this.getClass());
                    Method method = pd.getReadMethod();
                    XmlAttribute fieldXml = method.getAnnotation(XmlAttribute.class);
                    if (fieldXml != null) {
                        Object getValue = method.invoke(this);
                        if (getValue != null) {
                            stringBuffer.append(" " + fieldXml.name() + "=\"" + getValue.toString() + "\"");
                        }
                    }
                } catch (IntrospectionException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                }
            }
            stringBuffer.append(">");
        }
        return stringBuffer.toString();
    }
}
